package com.example.tamplate.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Info;
import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 *  上传文件控制器
 */
@Api(tags = "上传文件")
@RestController
@CrossOrigin
public class UploadController {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 绑定文件上传路径到uploadPath
     */
    @Value("${web.upload-path}")
//    @Value("C:/Users/Administrator/Desktop/wallpaper/后端/springboot-wallpaper/img")
    private String uploadPath;

    @ApiOperation(value = "文件图片")
    @PostMapping("/upload")
    public String upload(@RequestParam("img") MultipartFile uploadFile, HttpServletRequest request) {

        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        assert oldName != null;
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            // 文件保存
            uploadFile.transferTo(new File(folder, newName));
            return  newName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


}
